import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class HttpService {
  private headers = new Headers();
  constructor(private _http: Http) {
    /*set http request options*/
    /*this.headers.append('Authorization', 'Basic emFhc2RqZndlcmlvdXY6emFhc2RqZndlcmlvdXY=');
    this.headers.append('Content-Type', 'application/json');*/

    this.headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
  }
  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error); // for demo purposes only
    return Promise.reject(error.message || error);
  }

  get(url: string): Promise<any> {
    return this._http.get(url,{headers: this.headers})
      .toPromise()
      .then(response => response.json() || {})
      .catch(this.handleError);
  }

  post(url: string, body: any): Promise<any> {
    return this._http.post(url, body, {headers: this.headers})
      .toPromise()
      .then(response => response.json() || {})
      .catch(this.handleError);
  }

  patch(url: string, body: any): Promise<any> {
    return this._http.patch(url, JSON.stringify(body), {headers: this.headers})
      .toPromise()
      .then(response => response.json() || {})
      .catch(this.handleError);
  }

  put(url: string, body: any): Promise<any> {
    return this._http.put(url, JSON.stringify(body), {headers: this.headers})
      .toPromise()
      .then(response => response.json() || {})
      .catch(this.handleError);
  }

  delete(url: string): Promise<any>{
    return this._http.delete(url, {headers: this.headers})
      .toPromise()
      .then(response => response.json() || {})
      .catch(this.handleError);
  }

}
